﻿#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QPainter>
#include <QMouseEvent>
#include <QPropertyAnimation>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    resize(800,300);
    movePoint = height() / 2;
    animation = new QPropertyAnimation(this);
    animation->setTargetObject(this);
    animation->setDuration(500);
    animation->setEasingCurve( QEasingCurve::Linear );
    animation_1 = new QPropertyAnimation(this);
    animation_1->setTargetObject(this);
    animation_1->setDuration(500);
    animation_1->setEasingCurve( QEasingCurve::Linear );
    connect(animation,&QPropertyAnimation::valueChanged,this,[=](const QVariant& value){
        movePoint = value.toInt();
        update();
    });
    connect(animation_1,&QPropertyAnimation::valueChanged,this,[=](const QVariant& value){
        movePoint_1 = value.toInt();
        update();
    });
    connect(animation,&QPropertyAnimation::finished,this,[=]()
    {
        //animation_1->start();
    });
    connect(animation_1,&QPropertyAnimation::finished,this,[=]()
    {
        //animation_1->setDirection( QVariantAnimation::Backward );
        movePoint_1 = animation_1->startValue().toInt();
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint( QPainter::Antialiasing, true );
    painter.setPen( Qt::NoPen );
    painter.setBrush( isOff ? offBgBrush : onBgBrush );
    painter.drawRoundedRect(this->rect(), height() / 2, height() / 2);
    painter.setBrush( isOff ? offIndicatorBrush : onIndicatorBrush);
    painter.drawEllipse( QPoint(movePoint,height()/2), height() / 2 - 10, height() / 2 - 10);
    painter.setOpacity(0.5);
    painter.drawEllipse( QPoint(movePoint,height()/2), movePoint_1, movePoint_1);
    painter.setPen(Qt::white);
    painter.setFont(QFont("宋体", height() / 8));
    painter.drawText( rect(), Qt::AlignCenter, isOff ? offText : onText );
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if( event->button() == Qt::LeftButton)
    {
        isOff ? animation->setDirection( QVariantAnimation::Forward ) : animation->setDirection( QVariantAnimation::Backward );
        isOff ? animation->setEasingCurve( QEasingCurve::OutBounce ) : animation->setEasingCurve( QEasingCurve::InBounce );
        //isOff ? animation->setEasingCurve( QEasingCurve::OutQuad ) : animation->setEasingCurve( QEasingCurve::InQuad );
        isOff = !isOff;
        animation->start();
        //animation_1->start();
    }
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    animation->setStartValue(height() / 2);
    animation->setEndValue(width() - height() / 2);
    animation_1->setStartValue(height() / 2 - 40);
    animation_1->setEndValue(height() / 2 + 40);
}

